<?php
// Include config file
include('./common.php');

// Connect to database
$link = dbConnect();

// Attempt to auth user with database
$user = auth($_POST['username'], $_POST['password']);

if($user == ""){
   	echo "output=badLogin";
	return;
}

//see where we are so we know what we gotta do
switch($_POST['location']){
	case "inbox":
	case "outbox":
	case "trash":
		loadMessages($_POST['location'], $user['id']);
	break;
	
	case PM_READ_MESSAGE:
	case PM_TRASH_MESSAGE:
	case PM_DELETE_MESSAGE:
		//check if we are deleting multiples
		if(strrpos($_POST['messageID'], ":") !== false){
			deleteMultiple($user['id'], $_POST['messageID'], $_POST['location']);
		}else{
			//handle the normal status
			updateStatus($user['id'], $_POST['messageID'], $_POST['location'], $_POST['senderID'], $_POST['recipientID']);
		}
		
		//if it all went ok, update
		echo "output=".$_POST['location'];
	break;
	
	case "sendPrivateMessage":
		sendMessage($user['id'], $user['username']);
	break;
	
	case "checkMessages":
		$limit = $_POST['privateMessageLimit'];
		echo "output=success&username=".$user['username'].privateMessages($user['id'], $limit)."&admin=".checkAdminPermissions($user['id']);
	break;
}

//close the database
mysql_close($link);


function deleteMultiple($userID, $messages, $statusToUpdate){
	//we are going to build an array of the message IDs and also snag up the type they are (sender or receiver)
	$messageArray = explode(",", $messages);
	
	//loop through the new array and set each status
	for($i = 0; $i < count($messageArray); $i++){
		//explode again and send it off to the server
		$chunks = explode(":", $messageArray[$i]);
		
		//send it off
		$senderID = 0;
		$recipientID = 0;
		
		if($chunks[1] == "recipient"){
			$recipientID = $userID;
		}else{
			$senderID = $userID;
		}
		
		//time to update the status
		updateStatus($userID, $chunks[0], $statusToUpdate, $senderID, $recipientID);
	}
}

function updateStatus($userID, $messageID, $statusToUpdate, $sendID, $recipID){
	global $link;
	
	//make the IDs nice for mySQL
	$id = mysql_real_escape_string($messageID);
	$senderID = mysql_real_escape_string($sendID);
	$recipientID = mysql_real_escape_string($recipID);
	
	//figure out if the logged in user is the sender or the recipient
	$userType = "recipient";
	if($userID == $senderID){
		$userType = "sender";
	}
	
	//fire it off
	$result = mysql_query("UPDATE ".TABLE_PREFIX."_private SET ".$userType."Status = ".$statusToUpdate." WHERE messageID = ".$id);
	
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	//if they are doing a perma delete let's see if we should delete it from the dbase
	if($statusToUpdate == PM_DELETE_MESSAGE){
		$result = mysql_query("DELETE FROM 	".TABLE_PREFIX."_private 
							   WHERE messageID = ".$id." 
							   AND recipientStatus = ".PM_DELETE_MESSAGE." 
							   AND senderStatus = ".PM_DELETE_MESSAGE);
		if(!$result){
			echo "output=mySqlError&error=".mysql_error();
			return;
		}
	}
}

function loadMessages($location, $userID){
	global $link;
	
	$privateMessagesPerPage = mysql_real_escape_string($_POST['privateMessagesPerPage']);
	
	//use this for the dBase to get the PMs
	if (!isset($_POST['page']) || empty($_POST['page'])) {
    	$page = 1;
	}else{
		$page = mysql_real_escape_string($_POST['page']);
	}
	$offset = ($page - 1) * $privateMessagesPerPage;

	//setup some basic stuff that will help with the query
	$where = "";
	$and = "";
	
	//get the location we are in
	switch($location){
		
		default:
			//inbox is the default
			$where = "p.recipientID = ".$userID." AND recipientStatus != ".PM_DELETE_MESSAGE." AND recipientStatus != ".PM_TRASH_MESSAGE;
			$and = "u.userID = p.senderID";
		break;
		
		case "outbox":
			$where = "p.senderID = ".$userID." AND senderStatus != ".PM_DELETE_MESSAGE." AND senderStatus != ".PM_TRASH_MESSAGE;
			$and = "u.userID = p.recipientID";
		break;
		
		case "trash":
			//this trash one makes sure that what you see in the trash's "FROM" header is correct
			//so PMs from you to someone else will show from you and PMs that youv'e recieved will have the sender's name
			
			$where = "CASE WHEN p.recipientStatus = ".PM_TRASH_MESSAGE." 
					       THEN u.userID = p.senderID
                           WHEN p.senderStatus = ".PM_TRASH_MESSAGE." 
                           THEN u.userID = p.recipientID
                      END";
              
			$and = "p.recipientID = ".$userID." 
					AND p.recipientStatus = ".PM_TRASH_MESSAGE." 
					OR p.senderID = ".$userID." 
					AND p.senderStatus = ".PM_TRASH_MESSAGE;
		break;
	}
	
	// Build query to fetch the PMs
	$result = mysql_query("SELECT SQL_CALC_FOUND_ROWS p.*, u.username
							FROM ".TABLE_PREFIX."_users u, ".TABLE_PREFIX."_private p
							WHERE ".$where."
							AND ".$and."
							GROUP BY messageID
							ORDER BY sent DESC 
							LIMIT $offset,$privateMessagesPerPage");
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	//get the total PMs
	$totalResult = mysql_query("SELECT FOUND_ROWS() AS totalMessages");
	if(!$totalResult){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	$dataTotal = mysql_fetch_object($totalResult);
	
	//if we are down here then let's start outputting
	$output = "output=$location&totalMessages=".$dataTotal->totalMessages;
	$output .= "&currentPage=".$page."&totalPages=".ceil($dataTotal->totalMessages / $privateMessagesPerPage);
	$output .= "&messageCount=".mysql_num_rows($result);
	//loop through the results	
	for($i = 0; $i < mysql_num_rows($result); $i++){
		$pm = mysql_fetch_object($result);
		 
		//build the rest out
		$output .= "&pm" . $i . "id=" . $pm->messageID;
		$output .= "&pm" . $i . "subject=" . urlencode(stripslashes($pm->subject));
		$output .= "&pm" . $i . "message=" . urlencode(htmlspecialchars(stripslashes($pm->body)));
		$output .= "&pm" . $i . "username=" . urlencode(stripslashes($pm->username));
		$output .= "&pm" . $i . "sent=" . urlencode(timeParse($pm->sent, true));
		$output .= "&pm" . $i . "replied=" . urlencode(timeParse($pm->repliedTime, true));
		$output .= "&pm" . $i . "recipientID=" . $pm->recipientID;
		$output .= "&pm" . $i . "recipientStatus=" . $pm->recipientStatus;
		$output .= "&pm" . $i . "senderID=" . $pm->senderID;
		$output .= "&pm" . $i . "senderStatus=" . $pm->senderStatus;
	}
	
	echo $output;
}

function sendMessage($userID, $username) {
	global $link;
	
	$privateMessageLimit = $_POST['privateMessageLimit'];
	
	$recipient = mysql_real_escape_string($_POST['recipient']);
	$subject = mysql_real_escape_string($_POST['subject']);
	$message = mysql_real_escape_string($_POST['message']);
	$replyMessageID = mysql_real_escape_string($_POST['replyMessageID']);
	
	$recipientID = getUserID($recipient);
	
	//see if we've snagged a match
	if($recipientID == -1){
		echo "output=userNotFound";
		return;
	}
	
	//get the userID of the person we are sending this to (and a current count of the PMs they have)
	$result = mysql_query("SELECT COUNT(p.recipientID) AS currentMessages 
						   FROM ".TABLE_PREFIX."_private p
						   WHERE p.recipientID = ".$recipientID);
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	//let's see if we can send them a message
	$data = mysql_fetch_object($result);
	$currentMessageCount = $data->currentMessages;
	
	if($currentMessageCount >= $privateMessageLimit){
		//tell them it's full
		echo "output=mailboxFull";
		return;
	}
	
	//if we have the green light let's send the message!
	$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_private (recipientID, senderID, subject, body, sent)
						   VALUES ($recipientID, $userID, '$subject', '$message', ".time().")");
	
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	//if this was a reply message, make sure to update that messages reply time
	if($replyMessageID > 0){
		$result = mysql_query("UPDATE ".TABLE_PREFIX."_private SET repliedTime = ".time()." WHERE messageID = $replyMessageID");
		if(!$result){
			echo "output=mySqlError&error=".mysql_error();
			return;
		}
	}
	
	//if all is well let flash know
	echo "output=success";
	
	//send an email to the recipient letting them know they have a new private message
	$result = mysql_query("SELECT username, email FROM ".TABLE_PREFIX."_users WHERE userID = $recipientID");
	
	if(mysql_num_rows($result) > 0){
		$data = mysql_fetch_object($result);
		
		//send it off
		//$message = str_replace("\r", "\n", $message);
		$newPrivateMessage = $_POST['newPrivateMessage'];
		$clickToRead = $_POST['clickToRead'];
		$mailMessage = $data->username.",\n\n".$newPrivateMessage." ".$username.".\n\n".$clickToRead."\n\n";
		$mailMessage .= $_POST['installDirectory']."\n\n-----------------\n".$_POST['subjectWord'].": ".$_POST['subject']."\n\n";
		$mailMessage .= $_POST['messageWord'].":\n".$_POST['message'];
		
		sendMail($data->email, $newPrivateMessage." ".$username, $mailMessage, $_POST['boardName'], $_POST['boardEmail']);
	}
}
?>